package com.iflytek.springboot_medicine.controller;

import com.iflytek.springboot_medicine.entity.User;
import com.iflytek.springboot_medicine.entity.UserVO;
import com.iflytek.springboot_medicine.pojo.LoginPojo;
import com.iflytek.springboot_medicine.pojo.ResponseMessage;
import com.iflytek.springboot_medicine.pojo.PageResultPojo;
import com.iflytek.springboot_medicine.service.impl.UserServiceImpl;
import com.iflytek.springboot_medicine.util.JwtUtil;
import com.iflytek.springboot_medicine.util.RedisUtil;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import java.sql.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.HashMap;

@RestController
@RequestMapping("/user")
public class HomeController {

    private final UserServiceImpl userService;
    private final RedisUtil redisUtil;
    private final JwtUtil jwtUtil;
    private static final Logger log = LoggerFactory.getLogger(HomeController.class);

    @Autowired
    public HomeController(UserServiceImpl userService, RedisUtil redisUtil, JwtUtil jwtUtil) {
        this.userService = userService;
        this.redisUtil = redisUtil;
        this.jwtUtil = jwtUtil;
    }

    @PostMapping("/login")
    public ResponseMessage login(@RequestBody LoginPojo pojo) {
        log.debug("Login attempt for username: {}", pojo.getUsername());

        // 1. 验证用户
        User user = userService.login(pojo.getUsername(), pojo.getPassword());
        if (user == null) {
            log.warn("Login failed for username: {}", pojo.getUsername());
            return ResponseMessage.error("用户名或密码错误");
        }
        log.debug("User authenticated: {}", user);

        // 2. 生成JWT Token
        String token = jwtUtil.generateToken(user);
        log.debug("Generated token for user {}: {}", user.getName(), token);

        // 3. 将用户信息存入Redis（使用token作为key）
        String userKey = "USER:" + token;
        redisUtil.set(userKey, user, 60 * 60 * 24, TimeUnit.SECONDS); // 24小时过期

        // 4. 构建返回数据
        Map<String, Object> data = new HashMap<>();
        data.put("token", token);
        data.put("userInfo", new UserVO(user)); // 使用UserVO确保只返回必要的信息

        return ResponseMessage.success(data);
    }

    /**
     * 登录实现token,并验证code
     * @param param
     * @param request
     * @return
     */
//    @PostMapping(value = "/login",produces = {"application/json;charset=UTF-8"})
//    public ResponseMessage login(@RequestBody Map<String,String> param,
//                                 HttpServletRequest request,
//                                 HttpServletResponse response){
//        JSONObject jsonObject = new JSONObject();
//        String root_name = param.get("username");
//        String root_password = param.get("password");
//        User user = userService.login(root_name, root_password);
//        System.out.println(user);
//        //登录判断
//        if (user == null){
//            return ResponseMessage.error("login error!");
//        }else {
//            //登陆成功利用session存储账号密码
//            HttpSession session =request.getSession();
//            session.setAttribute("user",user);
//            String token = userService.getToken(user);
//            jsonObject.put("message", "login success!");
//            jsonObject.put("token", token);
//            jsonObject.put("username", user.getName());
//            jsonObject.put("role", user.getRole());
//            jsonObject.put("userId", user.getId());
//            Cookie cookie = new Cookie("token", token);
//            cookie.setPath("/");
//            response.addCookie(cookie);
//        }
//        return ResponseMessage.success(jsonObject);
//    }
    /**
     * 退出登录
     * @param request
     * @return
     */
//    @PostMapping(value = "logout")
//    public ResponseMessage unLogin(HttpServletRequest request){
//        HttpSession session = request.getSession();
//        session.removeAttribute("root");
//        return ResponseMessage.success("logout success!");
//    }

    @PostMapping("/logout")
    public ResponseMessage logout(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7);
            redisUtil.delete("USER:" + token);
            log.debug("Removed user info from Redis for token: {}", token);
        }
        return ResponseMessage.success("登出成功");
    }

    /**
     * 注册
     */
    @RequestMapping("/register")
    public ResponseMessage register(@RequestBody User user) {
        String register = userService.register(user.getUsername(), user.getPassword(), user.getRole());
        if (register.equals("注册成功")){
            return ResponseMessage.success(register);
        }
        return ResponseMessage.error(register);
    }


    @RequestMapping("/finduser/{username}")
    public ResponseMessage finduser(@PathVariable String username) {
          userService.findUserByUsername(username);
        System.out.println(username);
        return ResponseMessage.success("查询成功");
    }

    @RequestMapping("/finduserByName/{name}")
    public ResponseMessage findUserByName(@PathVariable String name) {
        User byName = userService.findByName(name);
        System.out.println(byName);
        return ResponseMessage.success(byName);
    }

    /**
     * 分页查询
     * @param pageNum
     * @param pageSize
     * @param name
     * @return
     */

    @RequestMapping("/findAllUsers")
    public ResponseMessage<PageResultPojo<User>> findAllUser(
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "10") int pageSize,
            @RequestParam(required = false) String name) {
        // 1. 构建分页请求对象
        // 2. 调用 Service 层进行分页查询
        Page<User> userPage = userService.findUsers(name, pageNum, pageSize);
        // 3. 封装分页结果
        PageResultPojo<User> pageResult = new PageResultPojo<>(
                userPage .getTotalElements(), // 总条数
                pageSize,                   // 每页条数
                pageNum,                    // 当前页码
                userPage .getContent()       // 当前页的数据
        );
        return ResponseMessage.success(pageResult);
    }

    /**
     * 增加用户
     * @param user
     * @return
     */
    @RequestMapping("/add")
    public ResponseMessage<User> addUser(@RequestBody User user) {
        if (user == null) {
            return ResponseMessage.error("增加失败");
        }
        userService.addUser(user);
        return ResponseMessage.success(user);
    }

    /**
     * 更新用户
     * @param user
     * @return
     */
    @RequestMapping("/update")
    public ResponseMessage<User> updateUser(@RequestBody User user) {
        if (user == null) {
            return ResponseMessage.error("更新失败");
        }
        userService.updateUser(user);
        return ResponseMessage.success(user);
    }

    @RequestMapping("/updatepassword")
    public ResponseMessage<User> updatePassword(@RequestBody User user){
        if (user.getPassword() == null || user.getNewPassword() == null) {
            return ResponseMessage.error("更新密码失败");
        }
        System.out.println("Controller数据："+ user.getNewPassword());

        userService.updatePassword(user);
        return ResponseMessage.success("更新成功");
    }




    /**
     * 删除用户
     * @param id
     * @return
     */
    @RequestMapping("/delete/{id}")
    public ResponseMessage deleteUser(@PathVariable int id) {
        if (id > 0) {
            userService.deleteUser(id);
        }
        return ResponseMessage.success();
    }

    /**
     * 批量删除
     */
    @RequestMapping("/deleteBatch")
    public ResponseMessage getUserById(@RequestBody List<Integer> ids) {
        if (ids == null || ids.size() == 0) {
            return ResponseMessage.error("删除失败");
        }
        userService.deleteAllInBatch(ids);
        return ResponseMessage.success();
    }
}
